package com.todo.biz.infrastructure.repository.impl;

import com.alibaba.fastjson.JSONObject;

import com.todo.biz.infrastructure.entity.condition.AssociateCondition;
import com.todo.biz.infrastructure.entity.po.BizAssociatePO;
import com.todo.biz.infrastructure.mapper.BizAssociateMapper;
import com.todo.biz.infrastructure.repository.BizAssociateRepository;
import com.todo.common.common.entity.response.page.PageResult;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.enums.BusinessSceneEnum;
import com.todo.common.common.exception.BizException;
import com.todo.common.utils.MathUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * @author zhangwenxiang
 * @date 2024/3/11 13:26
 * @description
 */
@Slf4j
@Repository("bizAssociateRepository")
public class BizAssociateRepositoryImpl implements BizAssociateRepository {

    @Resource
    private BizAssociateMapper bizAssociateMapper;

    @Override
    public BizAssociatePO queryBizAssociatePOById(Long id) {
        if (id == null || id < 0) {
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST);
        }
        return bizAssociateMapper.queryBizAssociatePOById(id);
    }

    @Override
    public Boolean insertBizAssociatePO(BizAssociatePO bizAssociatePO) {
        if (bizAssociatePO == null) {
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST);
        }
        if (!baseAssociateFieldCheck(bizAssociatePO)) {
            return false;
        }
        return bizAssociateMapper.insertBizAssociatePO(bizAssociatePO) > 0;
    }


    @Override
    public Boolean updateBizAssociatePOById(BizAssociatePO bizAssociatePO) {
        if (bizAssociatePO == null || bizAssociatePO.getId() == null) {
            log.error("BizAssociateRepository#updateBizAssociatePOById 根据主键更新关联信息失败，主键为空，默认不更新");
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST);
        }
        if (!baseAssociateFieldCheck(bizAssociatePO)) {
            return false;
        }
        return bizAssociateMapper.updateBizAssociatePOById(bizAssociatePO) > 0;
    }

    @Override
    public Boolean removeBizAssociatePOById(Long id) {
        if (id == null || id < 0) {
            log.error("BizAssociateRepository#removeBizAssociatePOById 根据主键删除关联信息失败，主键为空，默认不删除");
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST);
        }
        // 删除前确认数据是否正确
        BizAssociatePO bizAssociatePO = queryBizAssociatePOById(id);
        if (bizAssociatePO == null) {
            return true;
        }
        return bizAssociateMapper.removeBizAssociatePOById(id) > 0;
    }

    @Override
    public PageResult<BizAssociatePO> queryBizAssociateByCondition(AssociateCondition associateCondition) {
        PageResult<BizAssociatePO> pageResult = new PageResult<>();
        if (associateCondition == null) {
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST);
        }
        pageResult.setPageNum(associateCondition.getPageIndex());
        pageResult.setPageSize(associateCondition.getPageSize());
        long count = queryCountByCondition(associateCondition);
        if (count <= 0) {
            return pageResult;
        }
        pageResult.setPageCount((int) MathUtils.divide(count, associateCondition.getPageSize()));
        pageResult.setTotal(count);
        List<BizAssociatePO> bizAssociatePOList = bizAssociateMapper.queryBizAssociateByCondition(associateCondition);
        if (CollectionUtils.isEmpty(bizAssociatePOList)) {
            pageResult.setHasNext(false);
            return pageResult;
        }
        pageResult.setResults(bizAssociatePOList);
        pageResult.setCurrentIndex(bizAssociatePOList.get(0).getId());
        pageResult.setHasNext(bizAssociatePOList.size() >= associateCondition.getPageSize());
        return pageResult;
    }

    @Override
    public Long queryCountByCondition(AssociateCondition associateCondition) {
        if (associateCondition == null || associateCondition.getPageSize() <= 0) {
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST);
        }
        return bizAssociateMapper.queryCountByCondition(associateCondition);
    }

    @Override
    public List<BizAssociatePO> queryBizAssociateByBizIdAndScene(Long userId, Long bizId, BusinessSceneEnum scene) {
        if (bizId == null || scene == null || userId == null){
            return Collections.emptyList();
        }
        return bizAssociateMapper.queryBizAssociateByBizIdAndScene(userId, bizId, scene);
    }

    /**
     * 基础数据校验
     *
     * @param bizAssociatePO
     * @return
     */
    private boolean baseAssociateFieldCheck(BizAssociatePO bizAssociatePO) {
        if (bizAssociatePO == null) {
            return false;
        }
        if (bizAssociatePO.getRelationId() == null || bizAssociatePO.getUserId() == null) {
            log.error("BizAssociateRepository#baseAssociateFieldCheck 基础信息校验失败，核心数据为空 bizAssociatePO：【{}】", JSONObject.toJSONString(bizAssociatePO));
            return false;
        }
        if (bizAssociatePO.getRelationType() == null || bizAssociatePO.getBusinessScene() == null) {
            log.error("BizAssociateRepository#baseAssociateFieldCheck 基础信息校验失败，类型数据为空 bizAssociatePO：【{}】", JSONObject.toJSONString(bizAssociatePO));
            return false;
        }
        return true;
    }
}
